import { Component, Input, OnInit } from '@angular/core';
import { AlertController } from '@ionic/angular';
import { AppGlobalService } from 'src/app/shared/service/app-global.service';
import { EventService } from 'src/app/shared/service/event.service';
import { HttpService } from 'src/app/shared/service/http.service';
import { PageModalService } from 'src/app/shared/service/page-modal-service';

@Component({
  selector: 'app-decorate-info-list',
  templateUrl: './decorate-info-list.component.html',
  styleUrls: ['./decorate-info-list.component.scss'],
})
export class DecorateInfoListComponent implements OnInit {
  @Input() tagData: any;
  checkedAll = false;
  isOpen = false;
  dataIndex = -1;
  ids: any;
  saleTotal = 0;
  oTotal = 0;
  constructor(
    private httpService: HttpService,
    private appGlobalService: AppGlobalService,
    private pageModalService: PageModalService,
    private eventService: EventService,
    public alertController: AlertController,


  ) { }

  ngOnInit() {
    this.tagData.data.submit.content.pageNo = 2; // page返回初始PageNo 1 ;为了直接是否后面返回submit请求下一页
    if (this.tagData.data.headDiv) {
      this.tagData.data.headDiv.isOpen = true;
    }

     // 监听多选后
    if (this.eventService.eventEmit.listenerCount('auditNow') > 0) {
      this.eventService.eventEmit.removeListener('auditNow');
    }
    if (this.eventService.eventEmit.listenerCount('chooseAll') > 0) {
      this.eventService.eventEmit.removeListener('chooseAll');
    }
    this.eventService.eventEmit.on('auditNow', res => {
      console.log(res);
      const ids = [];
      this.tagData.data.data.forEach(element => {
        if (element.checked) {
          ids.push(element.id);
        }
      });
      if (ids.length === 0) {
        this.ids = '';
        return;
      }
      this.ids = ids.join(',');

      if (res.target) {
        if (res.beforeSubmit) {
          this.submitData(res);
        } else {
          this.showModal(res);
        }
      } else {
        // submit
        this.presentAlertWithMsgBtn(res);

      }

    });
    // 全选
    this.eventService.eventEmit.on('chooseAll', res => {
      if (res) {
        this.checkedAll = true;
        this.tagData.data.data.forEach(element => {

            element.checked = true;
            element.checkedGroup = true;


        });
      } else {
        this.tagData.data.data.forEach(element => {

            element.checked = false;
            element.checkedGroup = false;

        });
      }
      this.checkAll();
    });
  }


  async presentAlertWithMsgBtn(submit) {
    const that = this;
    const alert = await this.alertController.create({
      message: submit.text,
      buttons: [
        {
          text: "取消",
          role: "cancel",
          cssClass: "secondary"
        },
        {
          text: '确定',
          handler: () => {
            submit.content.id = this.ids;
            const params = {
              content: submit.content,
              id: submit.id,
              sessionId: localStorage.getItem("sessionId")
            };
            this.httpService.post("application/submit", params, res => {
              if (res.success) {
                this.appGlobalService.showToast(res.message, 1500, "middle");
                that.updateItem();

              }
            });
          }
        }
      ]
    });
    await alert.present();
  }
  submitData(link) {
    if (link.beforeSubmit.content.listKey) {
      link.beforeSubmit.content[link.beforeSubmit.content.listKey] = this.ids;
    } else {
      link.beforeSubmit.content.detailed_list_id = this.ids;
    }
    const params = {
      content: link.beforeSubmit.content,
      id: link.beforeSubmit.id,
      sessionId: localStorage.getItem("sessionId")
    };
    this.httpService.post("application/submit", params, res => {

      if (res.success) {
        localStorage.setItem('needRefresh', 'true');
        if (res.data.eventResult && link.params && link.params.eventReturnParam) {
          link.params[link.params.eventReturnParam] =  res.data.eventResult;
        }
        if (res.data.eventResult && link.params && link.params.eventResult) {
          link.params[link.params.eventResult] =  res.data.eventResult;
        }
        this.showModal(link);
      }
      if (res.message.length > 0) {
        this.appGlobalService.showToast(res.message, 1500, "middle");
      }

    });
  }

  showModal(link) {
    const that = this;
    link.params.id = this.ids;

    this.pageModalService.openPage(link, '', result => {
      if (result) {
        that.updateItem();
      }
    });

  }

  updateItem() {
    if (this.checkedAll) {
      this.appGlobalService.reloadCurrentPage();
      return;
    }
    const that = this;
    const page: any = this.appGlobalService.getCurrentTarget();
    if (page.params) {
    } else {
      page.params = {};
    }
    page.params.id = this.ids;
    this.httpService.post('application/page', page, async res => {
      const tagData = JSON.parse(res.script).views[0].tags;
      tagData.forEach(element => {
        if (element.style === 'decorateInfoListTag' && element.data && element.data.data) {
          element.data.data.forEach(newItem => {
            that.tagData.data.data.forEach(oItem => {
              if (oItem.id === newItem.id) {
                const index = that.tagData.data.data.indexOf(oItem);
                that.tagData.data.data.splice(index, 1, newItem);// 替换
              }
            });
          });
        }
        that.checkAll();

      });
    });
  }

  openPage(link) {
    this.pageModalService.openPage(link, '', res => {
      if (res) {

      }
    });
  }

   // 上滑加载
   loadMoreData(event) {
    if (this.tagData.data.data.length >= this.tagData.data.pageTotal) {
      event.target.disabled = true;
      // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
      // event.complete();
      return;
    }
    if (this.tagData.data.submit) {

      this.tagData.data.submit.sessionId = localStorage.getItem("sessionId");
    }

    this.httpService.post(
      "application/submit",
      this.tagData.data.submit,
      res => {
        // 请求数据成功
        if (res.success) {
          const resList = res.data.data;
          this.tagData.data.submit =  res.data.submit;
          // 追加返回数据
          if (resList && resList.length > 0) {
            // 追加数据
            resList.map(item => {
              this.tagData.data.data.push(item);
              this.checkAll();
            });
          } else {
            event.target.disabled = true;
            // 没有数据了
            // this.appGlobalService.showToast("没有数据了...", 1000, "middle");
          }
        } else {
          // 请求数据失败
          this.appGlobalService.showToast(res.message, 2000, "middle");
        }
        event.target.complete();
      },
      err => {

        // 请求数据失败
        this.appGlobalService.showToast(err.message, 2000, "middle");
        event.target.complete();
      }
    );
  }
  closeOpen() {
    this.isOpen = !this.isOpen;
    this.eventService.eventEmit.emit('isOpen', this.isOpen);
  }
  // 检查是否已经全选 价格合计
  checkAll() {
    let all = true;
    try {
      this.tagData.data.data.forEach(element => {
        if (!element.checked) {
          all = false;
          this.eventService.eventEmit.emit('chooseAllResult', all);
          throw new Error('break');
        }
      });
      this.checkedAll = all;
      this.eventService.eventEmit.emit('chooseAllResult', all);
    } catch (error) {
      if (error.message !== "break") { throw error; }
    }

    this.saleTotal = 0;
    this.oTotal = 0;
    this.tagData.data.data.forEach(element => {

      if (element.checked) {
        this.saleTotal +=  Number(element.firstRowLeft.header.fifthText.label) ;
        }
    });
    this.saleTotal = Math.fround(this.saleTotal * 100) / 100;
    this.eventService.eventEmit.emit('Total', {saleTotal:  this.saleTotal, oTotal: this.oTotal});
  }

  checkGroupAll(event, item) {

    item.checkedGroup = !item.checkedGroup;
    if (item.checkedGroup) {
      this.tagData.data.data.forEach(element => {
        if (element.type === item.type) {
          element.checked = true;
        }
      });
    } else {
      this.tagData.data.data.forEach(element => {
        if (element.type === item.type) {
          element.checked = false;
        }
      });
    }
    this.checkAll();
    event.stopPropagation();
  }
  checkItem(event, item) {
     item.checked = !item.checked;
     if (item.checked) {
      let all = true;
      try {
        this.tagData.data.data.forEach(element => {
          if (element.type === item.type && !element.checked) {
            all = false;
            throw new Error('break');
          }
        });

      } catch (error) {
        if (error.message !== "break") { throw error; }
      }
      if (!all) {
        this.tagData.data.data.forEach(element => {
          if (element.type === item.type ) {
            element.checkedGroup = false;
          }
        });
      } else {
        this.tagData.data.data.forEach(element => {
          if (element.type === item.type ) {
            element.checkedGroup = true;
          }
        });
      }


    } else {
      this.tagData.data.data.forEach(element => {
        if (element.type === item.type ) {
          element.checkedGroup = false;
        }
      });
    }

     this.checkAll();
     event.stopPropagation();
  }


}
